<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="format-detection" content="telephone=no">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta content="yes" name="apple-mobile-web-app-capable">
    <meta content="yes" name="apple-touch-fullscreen">
    <meta name="full-screen" content="yes">
    <meta content="default" name="apple-mobile-web-app-status-bar-style">
    <meta name="screen-orientation" content="portrait">
    <meta name="browsermode" content="application">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="x5-orientation" content="portrait">
    <meta name="x5-fullscreen" content="true">
    <meta name="x5-page-mode" content="app">
    <base target="_blank">
    <title>消息</title>
    <link href="${pageContext.request.contextPath}/static/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/css/chat.css">
    <script src="${pageContext.request.contextPath}/static/js/jquery-1.9.1.min.js"></script>
</head>

<body>

<img style="width:100%;height:100%" src="${pageContext.request.contextPath}/static/img/chat_bg.jpg">
<div class="abs cover contaniner" style="margin-top: 100px">
    <div class="abs cover pnl">
        <div class="top pnl-head" style="padding: 20px ; color: white;">
            <div id="userName"> 用户：张三<span style='float: right;color: green'>在线</span></div>
            <div id="chatMes" style="text-align: center;color: #6fbdf3;font-family: 新宋体">
                <!--正在和 <font face="楷体">张三</font> 聊天-->
            </div>
        </div>
        <!--聊天区开始-->
        <div class="abs cover pnl-body" id="pnlBody">
            <div class="abs cover pnl-left" id="initBackground" style="background-color: white; width: 100%">
                <div class="abs cover pnl-left" id="chatArea" style="display: none">
                    <div class="abs cover pnl-msgs scroll" id="show">
                        <div class="pnl-list" id="hists"><!-- 历史消息 --></div>
                        <div class="pnl-list" id="msgs">

                            <!-- 消息这展示区域 -->
                            <!-- <div class="msg guest"><div class="msg-right"><div class="msg-host headDefault"></div><div class="msg-ball">你好</div></div></div>
                             <div class="msg robot"><div class="msg-left" worker=""><div class="msg-host photo" style="background-image: url(img/avatar/Member002.jpg)"></div><div class="msg-ball">你好</div></div></div>-->
                        </div>
                    </div>

                    <div class="abs bottom pnl-text">
                        <div class="abs cover pnl-input">
                            <textarea class="scroll" id="context_text" wrap="hard" placeholder="在此输入文字信息..."></textarea>
                            <div class="abs atcom-pnl scroll hide" id="atcomPnl">
                                <ul class="atcom" id="atcom"></ul>
                            </div>
                        </div>

                        <div class="abs br pnl-btn" id="submit"
                             style="background-color: rgb(32, 196, 202); color: rgb(255, 255, 255);">
                            发送
                        </div>
                    </div>
                </div>

                <!--聊天区 结束-->

                <div class="abs right pnl-right">
                    <div class="slider-container hide"></div>
                    <div class="pnl-right-content">
                        <div class="pnl-tabs">
                            <div class="tab-btn active" id="hot-tab">好友列表</div>
                        </div>
                        <div class="pnl-hot">
                            <ul class="rel-list unselect" id="userlist">
                                <!--<li class="rel-item"><a onclick='showChat("张三")'>张三</a></li>
                                <li class="rel-item"><a onclick='showChat("李四")'>李四</a></li>-->
                            </ul>
                        </div>
                    </div>

                    <!--系统广播，已弃用-->
                    <div class="pnl-right-content" hidden>
                        <div class="pnl-tabs">
                            <div class="tab-btn active">系统广播</div>
                        </div>
                        <div class="pnl-hot">
                            <ul class="rel-list unselect" id="broadcastList">
                                <!--<li class="rel-item" style="color: #9d9d9d;font-family: 宋体">您的好友 张三 已上线</li>
                                <li class="rel-item" style="color: #9d9d9d;font-family: 宋体">您的好友 李四 已上线</li>-->
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    var toName;//发给xx姓名
    var username;//我的姓名
    var id;//我的id
    var allNames;//所有的用户姓名
    var onlineAllNames;//所有的在线用户姓名
    var historyContent;//历史聊天记录
    var toHistoryContent;//对方的历史聊天记录
    var ws;//websocket对象

    $(function () {
        var token = localStorage.getItem("token")
        if(token == null){//身份判定为招聘者
        //获取该招聘者的姓名并在聊天框上方展示
        $.ajax({
            url: "${pageContext.request.contextPath}/backStageLogin/getUsername",
            success: function (res) {
                username = res.manageName;
                id = res.manageId;
                //显示在线信息
                $("#userName").html(" 用户：" + res + "<span style='float: right;color: green'>在线</span>");
            },
            async: false
        })

        //获取所有在线者的姓名
        $.ajax({
            url: "${pageContext.request.contextPath}/personCenter/isOnline",
            success: function (res) {
                onlineAllNames = res.data;
            },
            async: false
        })

        //显示在线或者离线，根据token值是否为null，若是招聘者，获取所有求职者名单，若是求职者，获取所有招聘者名单
        $.ajax({
            url: "${pageContext.request.contextPath}/personCenter/getAllUsername",
            headers:{"token": token},
            success: function (res) {
                if (res.resultCode === 200) {
                    allNames = res.data;
                    var userlistStr = "";
                    for (let i = 0; i < allNames.length; i++) {
                        if (allNames[i] !== username) {
                            var flag = 0;//如果为0，说明不在线，否则为1，在线
                            for (let j = 0; j < onlineAllNames.length; j++) {
                                if (allNames[i] === onlineAllNames[j]) {
                                    flag = 1;
                                }
                            }
                            if (flag === 0) {
                                userlistStr += "<li class=\"rel-item\"><a onclick='showChat(\"" + allNames[i] + "\")'>" + allNames[i] + '<span style="color: #00b7ee">普通用户(离线)</span>' + "</a></li>";
                            } else {
                                userlistStr += "<li class=\"rel-item\"><a onclick='showChat(\"" + allNames[i] + "\")'>" + allNames[i] + '<span style="color: #00b7ee">普通用户(在线)</span>' + "</a></li>";
                            }
                        }
                    }
                    $("#userlist").html(userlistStr);
                }
            },
            async: false
        })


        //创建webSocket对象
        ws = new WebSocket("ws://localhost:8080${pageContext.request.contextPath}/chat");
        //给ws绑定事件
        ws.onopen = function () {
            //在建立连接后需要做什么事？
            //显示在线信息
            $("#userName").html(" 用户：" + username + "<span style='float: right;color: green'>在线</span>");
        }

        //接收到服务端推送的消息后触发
        ws.onmessage = function (evt) {
            //获取服务端推送过来的消息
            var dataStr = evt.data;
            //将dataStr 转换为json对象
            var res = JSON.parse(dataStr);
            //判断是否是系统消息
            if (res.isSystem) {
                //系统消息
                var names = res.message;
                //1,好友列表展示
                //2,系统广播的展示
                var broadcastListStr = "";
                for (var name of names) {
                    if (name != username) {
                        broadcastListStr += "<li class=\"rel-item\" style=\"color: #9d9d9d;font-family: 宋体\">您的好友 " + name + " 已上线</li>";
                    }
                }
                //渲染好友列表和系统广播
                $("#broadcastList").html(broadcastListStr);

            } else {
                //不是系统消息
                //将服务端推送的消息进行展示
                var str = "<div class=\"msg robot\"><div class=\"msg-left\" worker=\"\"><div class=\"msg-host photo\" style=\"background-image: url(${pageContext.request.contextPath}/static/img/avatar/Member002.jpg)\"></div><div class=\"msg-ball\">" + res.message + "</div></div></div>";
                if (toName === res.fromName) {//说明该用户在线且打开 的是 发送该条信息的人 的聊天框
                    $("#msgs").append(str);
                    historyContent += str;
                    //将消息存到数据库
                    $.ajax({
                        type: "post",
                        url: "${pageContext.request.contextPath}/chatHistory/updateChatContent",
                        data: {
                            sponsorName: username,
                            recipientName: toName,
                            chatContent: historyContent,
                            chatStatus : 1 //设为已读
                        },
                        success: function (res) {
                        },
                        async: false
                    })
                }else{
                    //说明该用户虽然在线但是并未打开 发送该条信息的人 的聊天框，此时将该条信息自动存入
                    //数据库即可 1 获取聊天记录  2 添加聊天记录并设置为未读消息
                    $.ajax({
                        url: "${pageContext.request.contextPath}/chatHistory/getChatContent?sponsorName=" + username + "&recipientName=" + res.fromName,
                        success: function (res) {
                            console.log(res)
                            if (res.resultCode === 200) {
                                if(res.data == null) {
                                    historyContent = "";
                                }else {
                                    historyContent = res.data;
                                }
                                historyContent += str;
                            }
                        },
                        async: false
                    })
                    //存到数据库
                    $.ajax({
                        type: "post",
                        url: "${pageContext.request.contextPath}/chatHistory/updateChatContent",
                        data: {
                            sponsorName: username,
                            recipientName: res.fromName,
                            chatContent: historyContent,
                            chatStatus : 0
                        },
                        success: function (res) {
                            console.log("用户虽然在线但是并未打开 发送该条信息的人 的聊天框，此时将该条信息自动存入数据库")
                        }
                    })

                }
            }
        }

        ws.onclose = function () {
            //显示离线信息
            $("#userName").html(" 用户：" + username + "<span style='float: right;color: red'>离线</span>");
        }
    }
})

    function showChat(name) {
        var token = localStorage.getItem("token");
        toName = name;
        //现在聊天对话框
        $("#chatArea").css("display", "inline");
        //清空聊天区
        $("#msgs").html("");

        //显示“正在和谁聊天”
        $("#chatMes").html("正在和 <font face=\"楷体\">" + toName + "</font> 聊天");

        //取出聊天内容即可
        $.ajax({
            url: "${pageContext.request.contextPath}/chatHistory/getChatContent?sponsorName=" + username + "&recipientName=" + toName,
            success: function (res) {
                var reason;
                if (res.resultCode === 200) {
                    if(res.data == null) {
                        historyContent = "";
                    }else {
                        historyContent = res.data;
                    }
                    $("#msgs").html(historyContent);
                }
            },
            async: false
        })
    }

    $("#submit").click(function () {
        //获取输入的内容
        var data = $("#context_text").val();
        //清除输入区的内容
        $("#context_text").val("");

        var json = {"toName": toName, "message": data};

        //将数据展示在聊天区
        var str = "<div class=\"msg guest\"><div class=\"msg-right\"><div class=\"msg-host headDefault\"></div><div class=\"msg-ball\">" + data + "</div></div></div>";
        $("#msgs").append(str);

        if (data !== null) {
            if(historyContent == null){
                historyContent = "";
            }
            historyContent += str;
        }
        //将消息存到数据库
        $.ajax({
            type: "post",
            url: "${pageContext.request.contextPath}/chatHistory/updateChatContent",
            data: {
                sponsorName: username,
                recipientName: toName,
                chatContent: historyContent
            },
            success: function (res) {
                console.log(res)
            },
            async: false
        })

        //判断是否发送数据给服务端
        var isOnline = 0;//若为0，说明对方不在线，此时需要手动在数据库更新。
        for (let i = 0; i < onlineAllNames.length; i++) {
            if (toName === onlineAllNames[i]) {
                ws.send(JSON.stringify(json));
                isOnline = 1;
                break;
            }
        }
        if (isOnline === 0) {
            //手动在数据库更新   1.取出  2.更改

            //从数据库取出聊天内容
            $.ajax({
                url: "${pageContext.request.contextPath}/chatHistory/getChatContent?sponsorName=" + toName + "&recipientName=" + username,
                success: function (res) {
                    if (res.resultCode === 200) {
                        if (res.data == null){
                            toHistoryContent="";
                        }else{
                            toHistoryContent = res.data;
                        }
                        var strs = "<div class=\"msg robot\"><div class=\"msg-left\" worker=\"\"><div class=\"msg-host photo\" style=\"background-image: url(${pageContext.request.contextPath}/static/img/avatar/Member002.jpg)\"></div><div class=\"msg-ball\">" + data + "</div></div></div>";
                        toHistoryContent += strs;
                        //2 更改
                        $.ajax({
                            type: "post",
                            url: "${pageContext.request.contextPath}/chatHistory/updateChatContent",
                            data: {
                                sponsorName: toName,
                                recipientName: username,
                                chatContent: toHistoryContent
                            },
                            success: function (res) {
                                console.log(res)
                            }
                        })
                    }
                }
            })

        }else {

        }
    });

</script>
</body>
</html>